package com.example.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class BorrowDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "LibrarySystem";
    private static final int DATABASE_VERSION = 1;
    public static final String TABLE_BORROW_RECORDS = "borrow_records";

    // 列名
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_BOOK_ID = "book_id";
    public static final String COLUMN_READER_ID = "reader_id";
    public static final String COLUMN_BORROW_DATE = "borrow_date";
    public static final String COLUMN_RETURN_DATE = "return_date";
    public static final String COLUMN_STATUS = "status"; // 0:未归还, 1:已归还

    public BorrowDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTableQuery = "CREATE TABLE " + TABLE_BORROW_RECORDS + " (" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_BOOK_ID + " INTEGER, " +
                COLUMN_READER_ID + " INTEGER, " +
                COLUMN_BORROW_DATE + " TEXT, " +
                COLUMN_RETURN_DATE + " TEXT, " +
                COLUMN_STATUS + " INTEGER DEFAULT 0, " +
                "FOREIGN KEY(" + COLUMN_BOOK_ID + ") REFERENCES " +
                BookDatabaseHelper.TABLE_BOOKS + "(" + BookDatabaseHelper.COLUMN_ID_BOOK + "), " +
                "FOREIGN KEY(" + COLUMN_READER_ID + ") REFERENCES " +
                ReaderDatabaseHelper.TABLE_READERS + "(" + ReaderDatabaseHelper.COLUMN_ID + "))";
        db.execSQL(createTableQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_BORROW_RECORDS);
        onCreate(db);
    }

    // 添加借阅记录
    public boolean addBorrowRecord(int bookId, int readerId, String borrowDate) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_BOOK_ID, bookId);
        values.put(COLUMN_READER_ID, readerId);
        values.put(COLUMN_BORROW_DATE, borrowDate);
        values.put(COLUMN_STATUS, 0); // 设置为未归还状态

        long result = db.insert(TABLE_BORROW_RECORDS, null, values);
        db.close();
        return result != -1;
    }
}